// src/server/client_handler.cpp
#include "client_handler.h"
#include "server.h"
#include <iostream>
#include <cstring>
#include <unistd.h>

ClientHandler::ClientHandler(int client_socket, ChatServer* server)
    : client_socket(client_socket), server(server) {}

ClientHandler::~ClientHandler() {
    close(client_socket);
}

void ClientHandler::start() {
    // 创建新线程处理客户端连接
    pthread_create(&thread, nullptr, handle_client_static, this);
    pthread_detach(thread); // 分离线程，自动回收资源
}

void* ClientHandler::handle_client_static(void* arg) {
    ClientHandler* handler = static_cast<ClientHandler*>(arg);
    handler->handle_client();
    return nullptr;
}

void ClientHandler::handle_client() {
    char buffer[1024];
    ssize_t bytes_received;
    
    // 读取客户端发送的数据
    while ((bytes_received = read(client_socket, buffer, sizeof(buffer))) > 0) {
        buffer[bytes_received] = '\0';
        std::string message(buffer);
        
        // 处理消息并广播给其他客户端
        server->broadcast_message(message, client_socket);
    }
    
    // 客户端断开连接
    server->remove_client(client_socket);
}

int ClientHandler::getClientSocket() const {
    return client_socket;
}    